from sessioManagementMainWindow_ui import Ui_sessioManagementMainWindow
from sessioManagementSetting_ui import Ui_sessioManagementSetting
from sessioManagementClassTimeConfilct_ui import Ui_sessioManagementClassTimeConfilct
from PySide6.QtWidgets import QApplication,QMainWindow,QMessageBox,QListWidgetItem,QDialog,QRadioButton,QCheckBox,QSpacerItem,QSizePolicy,QGridLayout,QTimeEdit,QGroupBox
from PySide6.QtCore import Qt,Slot,QDate,QTime
from loger import log
import sys
import inc_db as db
import sqlite3
class sessionManagement(QMainWindow):
    def __init__(self, parent = None ):
        super().__init__(parent)
        self.UserRoleID=Qt.UserRole
        self.userRoleTitle=Qt.UserRole+1
        self.ui=Ui_sessioManagementMainWindow()
        self.ui.setupUi(self)
        self.setWindowModality(Qt.WindowModal)

        self.ui.btn_add.clicked.connect(self.onbtnAdd)
        self.refreshlist()

    def onbtnAdd(self):
        title=self.ui.examName.text()
        sessionNum=self.ui.sessionNum.value()
        teacherNum=self.ui.teacherNum.value()
        roomNum=self.ui.roomNum.value()
        maxExamID=int(db.getData("maxExamID"))
        if(len(title)<3):
            QMessageBox.warning(self,"重试","监考名称过短")
            return False
        (s,r)=db.runsql(f"INSERT INTO `exam_list` (`ID`, `title`, `sessionNum`, `teacherNum`, `roomNum`) VALUES ({maxExamID+1}, '{title}', {sessionNum}, {teacherNum}, {roomNum})")
        if(s):
            db.setData("maxExamID",maxExamID+1)
            db.setData("activeExamID",maxExamID+1)
            QMessageBox.information(self,"添加成功",f"已经成功添加{title}")
            self.refreshlist()
    @Slot()
    def on_btn_del_clicked(self):
        log.debug("on_btn_del_clicked")
        t1=db.getData("test1")
        db.setData("test1",int(t1)+1)
    def refreshlist(self):
        self.ui.listWidget.clear()
        (s,r)=db.runsql(f"select ID,title,sessionNum,teacherNum,roomNum from exam_list where ID={db.getData("activeExamID")}")
        r=r.fetchone()
        if(not s):QMessageBox.critical(self,"错误",f"考试列表读取失败 {str(r)}")
        if r is not None:
            self.ui.examName.setText(r[1])
            self.ui.sessionNum.setValue(r[2])
            self.ui.teacherNum.setValue(r[3])
            self.ui.roomNum.setValue(r[4])
        
            parentWindow=self.parent()   #修改父窗口标题
            if parentWindow is not None: parentWindow.setWindowTitle(f"{r[1]} - 监考表")
            (_,r)=db.runsql("select ID,title,sessionNum,teacherNum,roomNum from exam_list order by ID desc")
            
            for i in r.fetchall():
                item=QListWidgetItem(f"{i[1]}")
                item.setData(self.UserRoleID,i[0])
                item.setData(self.userRoleTitle,i[1])
                self.ui.listWidget.addItem(item)
                

    @Slot()
    def on_listWidget_itemClicked(self):
        item=self.ui.listWidget.currentItem()
        log.debug(item.data(self.UserRoleID))
        log.debug(item.data(self.userRoleTitle))
        (_,r)=db.runsql(f"select sessionNum,teacherNum,roomNum from exam_list where ID={item.data(self.UserRoleID)}")
        r=r.fetchone()
        self.ui.examName.setText(item.data(self.userRoleTitle))
        self.ui.sessionNum.setValue(r[0])
        self.ui.teacherNum.setValue(r[1])
        self.ui.roomNum.setValue(r[2])


    @Slot()
    def on_btn_active_clicked(self):
        item=self.ui.listWidget.currentItem()
        activeID=item.data(self.UserRoleID)
        db.setData("activeExamID",activeID)
        (s,_)=db.runsql(f"UPDATE `exam_list` SET `title`='{self.ui.examName.text()}', `sessionNum` = {self.ui.sessionNum.value()},`teacherNum`={self.ui.teacherNum.value()}, `roomNum`={self.ui.roomNum.value()} WHERE (`ID`={item.data(self.UserRoleID)})")
        if(s is False):
            QMessageBox.critical(self,"错误","保存失败")
        self.refreshlist()
    @Slot()
    def on_btn_del_clicked(self):
        item=self.ui.listWidget.currentItem()
        ID=item.data(self.UserRoleID)
        log.debug(f"ID:{ID}\tdel")
        db.runsql(f"DELETE FROM `exam_list` WHERE (`ID`={ID});")
        ### TODO 删除相关信息###
        if(int(ID)==int(db.getData("activeExamID"))):
            (s,r)=db.runsql(f"select id from exam_list order by id desc limit 1")
            r=r.fetchone()
            if r is None:
                db.setData("activeExamID",0)
            else:
                db.setData("activeExamID",r[0])
        self.refreshlist()
    @Slot()
    def on_btn_setting_clicked(self):
        settingwindow=settingWin(self)
        settingwindow.show()
class settingWin(QMainWindow):
    def __init__(self, parent = None ):
        super().__init__(parent)
        self.ui=Ui_sessioManagementSetting()
        self.ui.setupUi(self)
        self.setWindowModality(Qt.WindowModal)
        self.ui.dateEdit.setDisplayFormat("yyyy-MM-dd")
        self.ui.timeEdit.setDisplayFormat("HH:mm")
        self.ui.timeEdit_2.setDisplayFormat("HH:mm")
        self.examID=int(db.getData("activeExamID"))
        self.currentID=0
        self.initdata()
    def initdata(self):
        if self.examID is None or self.examID==0:
            return False
        
        (s,r)=db.runsql(f"select title,sessionNum,teacherNum,roomNum from exam_list where ID={self.examID}")
        r=r.fetchone()
        self.nowTitle=r[0]
        self.nowSessionNum=r[1]
        self.nowteacherNum=r[2]
        self.nowRoomNum=r[3]
        self.setWindowTitle(f"{r[0]} - 设置")
        self.getSettingtoFace()
        for i in range(r[1]):
            item=QListWidgetItem(f"第{i+1}场")
            item.setData(Qt.UserRole,i)
            self.ui.listWidget.addItem(item)

    @Slot()
    def on_pushButton_clicked(self):
        if(self.ui.listWidget.currentItem() is None):
            QMessageBox.warning(self,"","请选择考试科目")
            return False
        settingDialog=classTimeConfilct(self)
        settingDialog.exec()
        log.debug("setting1")
        pass
    def saveface(self):
        title=self.ui.subject.toPlainText()
        if title=="七年级\n八年级\n九年级":title=""
        date=self.ui.dateEdit.text()
        startTime=self.ui.timeEdit.text()
        endTime=self.ui.timeEdit_2.text()
        (s,_)=db.runsql(f"INSERT OR IGNORE INTO exam_info (examID,session) VALUES ({self.examID},{self.currentID})")
        (s,r)=db.runsql(f"UPDATE `exam_info` SET `title`='{title}', `session_date`='{date}',`start_time`='{startTime}', `end_time`='{endTime}' WHERE (`examID`={self.examID}) AND (`session`={self.currentID})")
        if(not s):
            QMessageBox.critical(self,"数据保存错误",str(r))
    @Slot()
    def on_listWidget_clicked(self):
        self.saveface() #保存当前界面
        item=self.ui.listWidget.currentItem()
        self.currentID=item.data(Qt.UserRole)
        self.getSettingtoFace() #刷新选中界面

    def setDate(self,date:str):
        qd=QDate.fromString(date,"yyyy-MM-dd")
        if qd.isValid():
            self.ui.dateEdit.setDate(qd)
        else:
            self.ui.dateEdit.setDate(QDate(2000,1,1))
            log.error("日期解析失败！")
    def setTime(self,time:str,widget:QTimeEdit):
        qt=QTime.fromString(time,"HH:mm")
        if qt.isValid():
            widget.setTime(qt)
        else:
            log.error("时间解析失败！")
    def getSettingtoFace(self):
        (s,r)=db.runsql(f"select title,session_date,start_time,end_time from exam_info where examID={self.examID} and session={self.currentID}")
        if(s):
            r=r.fetchone()
            if(r is None):
                self.ui.subject.setPlainText("七年级\n八年级\n九年级")
                self.ui.dateEdit.setDate(QDate.currentDate())
            else:
                if(r[0]==""):
                    self.ui.subject.setPlainText("七年级\n八年级\n九年级")
                else:
                    self.ui.subject.setPlainText(r[0])
                self.setDate(r[1])
                self.setTime(r[2],self.ui.timeEdit)
                self.setTime(r[3],self.ui.timeEdit_2)
                pass
        else:
            QMessageBox.critical(self,"查询错误",str(r))
class classTimeConfilct(QDialog):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.ui=Ui_sessioManagementClassTimeConfilct()
        self.ui.setupUi(self)
        self.setColNum(self.ui.grade7Layout,[1,1,1,1])
        self.setColNum(self.ui.grade8Layout,[1,1,1,1])
        self.setColNum(self.ui.grade9Layout,[1,1,1,1])
        self.setColNum(self.ui.classLayout,[1,1])

        self.db=sqlite3.connect(db.root.parent/"timetable/classbook.db")
        self.cur=self.db.cursor()
        r=self.cur.execute("select `sn`, `value` from `lable` where `type`='week';")
        r=r.fetchall()
        for i in r:
            radio=QRadioButton(f"{i[1]}")
            radio.setProperty("sn", i[0])  
            self.ui.weekLayout.addWidget(radio) 
        self.ui.weekLayout.addItem(QSpacerItem(20,20,QSizePolicy.Minimum,QSizePolicy.Expanding))
        r=self.cur.execute("select `sn`, `value` from `lable` where `type`='session';")
        r=r.fetchall()
        for i in r:
            check_=QCheckBox(f"{i[1]}")
            check_.setProperty("sn", i[0])  
            self.ui.classLayout.addWidget(check_)


        classGrade=self.getGrade()
        for i in classGrade:
            if(classGrade[i]==7):
                self.ui.grade7Layout.addWidget(QCheckBox(i))
            if(classGrade[i]==8):
                self.ui.grade8Layout.addWidget(QCheckBox(i))
            if(classGrade[i]==9):
                self.ui.grade9Layout.addWidget(QCheckBox(i))
        if(self.initdate() is False):self.close()
    def initdate(self):
        parent=self.parent()
        item=parent.ui.listWidget.currentItem()
        self.currentID=item.data(Qt.UserRole)
        self.examID=int(db.getData("activeExamID"))
        (s,r)=db.runsql(f"select confilct_week,confilct_class_time,confilct_class_name from exam_info where examID = {self.examID} and session={self.currentID}")
        if(s):
            r=r.fetchone()
            log.debug(str(r))
            if(r[0] is not None):
                for radio in self.ui.groupBox.findChildren(QRadioButton):
                    if int(radio.property("sn"))==int(r[0]):
                        radio.setChecked(True)
                        break
                self.setcheckBoxChecked(self.ui.groupBox_2,r[1])
                self.setcheckBoxChecked(self.ui.groupBox_3,r[2])
                self.setcheckBoxChecked(self.ui.groupBox_4,r[2])
                self.setcheckBoxChecked(self.ui.groupBox_5,r[2])
    
    def setcheckBoxChecked(self,groupbox:QGroupBox,selected :str):
        selected=selected.split(",")
        for checkbox_ in  groupbox.findChildren(QCheckBox):
            if(checkbox_.text() in selected):
                checkbox_.setChecked(True)
            if(str(checkbox_.property("sn")) in selected):
                checkbox_.setChecked(True)

    

    @Slot()
    def on_btn_save_clicked(self):
        log.debug("on_btn_save_clicked")
        weeksn=None
        for radio in self.ui.groupBox.findChildren(QRadioButton):
            if radio.isChecked():
                # 获取显示文本
                weeksn=radio.property("sn")
                log.debug(f"选中的选项：{radio.text()} ,({weeksn})")
                break
        if weeksn is None:
            QMessageBox.critical(self,"请选择星期","请选择课时冲突的星期")
            return False
        sessionlist=[]
        for checkbox in self.ui.groupBox_2.findChildren(QCheckBox):
            if checkbox.isChecked():
                sessionlist.append(int(checkbox.property("sn")))
        if len(sessionlist)==0 :
            QMessageBox.critical(self,"请选择","请选择课时冲突的课时")
            return False
        classList=[]
        classList+=self.get_checked_class(self.ui.groupBox_3)   #七年级
        classList+=self.get_checked_class(self.ui.groupBox_4)   #八年级
        classList+=self.get_checked_class(self.ui.groupBox_5)   #九年级
        if len(classList)==0:
            QMessageBox.critical(self,"请选择","请选择课时冲突的班级")
            return False
        print(sessionlist)
        print(classList)
        sessionlist=[str(x) for x in sessionlist]
        sessionlist=",".join(sessionlist)
        classList=",".join(classList)
        print(sessionlist)
        print(classList)
        parent=self.parent()
        (s,_)=db.runsql(f"INSERT OR IGNORE INTO exam_info (examID,session) VALUES ({parent.examID},{parent.currentID})")
        (s,r)=db.runsql(f"UPDATE `exam_info` SET `confilct_week`='{weeksn}', `confilct_class_time`='{sessionlist}',`confilct_class_name`='{classList}' WHERE (`examID`={parent.examID}) AND (`session`={parent.currentID})")
        if(s):
            QMessageBox.information(self,"成功","保存成功")
    def get_checked_class(self,groupbox:QGridLayout)->list[str]:
        checked_box=[]
        for c in groupbox.findChildren(QCheckBox):
            if c.isChecked():
                checked_box.append(c.text())
        return checked_box
    def getGrade(self):
        classGrade={}
        r=self.cur.execute("select class from main group by class")
        r=r.fetchall()
        classList=[i[0] for i in r]
        for i in classList:
            r=self.runsql(f"select real_course from main where class='{i}' group by real_course")
            course={j[0] for j in r}
            if('化学' in course):
                classGrade[i]=9
            elif('物理' in course and '生物' in course):
                classGrade[i]=8
            elif('物理' not in course and '化学' not in course):
                classGrade[i]=7

        return classGrade
    def setColNum(self,grouplayout:QGridLayout,colW:list[int])->None:
        for i,v in enumerate(colW) :
            grouplayout.setColumnStretch(i,v)

    def get_checked_checkboxes(self, group_box):
        """获取指定groupBox中所有选中的QCheckBox"""
        checked_boxes = []
        # 遍历groupBox中的所有QCheckBox子组件
        for checkbox in group_box.findChildren(QCheckBox):
            if checkbox.isChecked():
                # 存储选中的checkbox的文本和自定义属性（如sn）
                checked_info = {
                    "text": checkbox.text(),
                    "sn": checkbox.property("sn")  # 如果有设置sn属性
                }
                checked_boxes.append(checked_info)
        return checked_boxes
    def runsql(self,sql):
        try:
            r=self.cur.execute(sql)
        except sqlite3.Error as e:
            self.db.rollback()
            log.critical(str(e))
            return None
        else:
            r=r.fetchall()
            self.db.commit()
            return r

if __name__ =="__main__":
    app=QApplication()
    mywi=sessionManagement()
    mywi.show()
    # dia=classTimeConfilct()
    # dia.show()
    sys.exit(app.exec())